package insight.sm.delegates;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONStringer;

/**
 * 
 * AjaxJSONDelegate class set json object in HttpServletResponse and send back
 * to the UI.
 * 
 */
public class AjaxDelegate {

	/**
	 * 
	 * @param jarray
	 *            holds the response values
	 * @param res
	 *            is HttpServletResonse.
	 */
	public static void setResponse(final JSONArray jarray,
			final HttpServletResponse res) {
		try {
			Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8");
			w.write(jarray.toString());
			w.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 
	 * @param content
	 *            holds the response values
	 * @param res
	 *            is HttpServletResonse.
	 */
	public static void setTextResponse(final String content,
			final HttpServletResponse res) {
		try {
			Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8");
			w.write(content);
			w.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 
	 * @param jsonStringer
	 *            holds response values
	 * @param res
	 *            is HttpServletResonse.
	 */
	public static void setResponse(final JSONStringer jsonStringer,
			final HttpServletResponse res) {
		try {
			Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8");
			w.write(jsonStringer.toString());
			w.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static void setResponse(final JSONObject obj,
			final HttpServletResponse res) {
		try {
			Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8");
			// System.out.print(obj.toString());
			w.write(obj.toString());
			w.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static void setResponse(InputStream inStream,
			HttpServletResponse response, String type) throws IOException {
		if (type != null)
			response.setContentType(type);
		IOUtils.copy(inStream, response.getOutputStream());

	}
}